﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Kingdee.BOS.Orm.DataEntity;
using Kingdee.BOS.Core.Bill.PlugIn;
using Kingdee.BOS.Core.Bill.PlugIn.Args;
using Kingdee.BOS.Core.DynamicForm;
using Kingdee.BOS.Util;
using System.ComponentModel;


namespace Zy.K3Cloud.SaleOrderSavePlugInCheckFactoryNumber
{
    /// <summary>
    /// [单据插件]销售订单保存前校验出厂编码范围与销售数量是否相符
    /// </summary>
    [Description("[单据插件]销售订单保存前校验出厂编码范围与销售数量是否相符"), HotUpdate]
    public class ConfirmBeforeSaveBillPlugIn: AbstractBillPlugIn
    {

        private static bool CheckCount(DynamicObject entityObj)
        {
            string fn = entityObj["F_HY_Text1"] != null ? entityObj["F_HY_Text1"].ToString() : ""; //出厂编码字段
            int count = Convert.ToInt32(entityObj["Qty"]); //销售数量
            string fntype = entityObj["F_ora_fn_type"] != null ? entityObj["F_ora_fn_type"].ToString() : "";//编码类别
            int fn_count;
            if (fn != "")
            {
                String[] fns = fn.Split('-');
                if (fns.Length == 1)
                {
                    fn_count = 1;
                }
                else if (fns.Length == 2)
                {
                    fn_count = Convert.ToInt32(fns[1]) - Convert.ToInt32(fns[0]) + 1;
                }
                else
                {
                    //编码有多个-符号，此种情况按不相符处理
                    fn_count = -999;
                }

                return fn_count == count; //编码容量与销售数量不相符则提示需要更新条码；
            }
            else if(fntype != "")
            {
                return false;
            }else
            {
                return true;
            }
        }

        private bool doSave = false;

        public override void BeforeSave(BeforeSaveEventArgs e)
        {
            base.BeforeSave(e); 
            if (doSave) { doSave = false; return; }  
            
            // 如果要交互，就要全面接管保存操作           
            e.Cancel = true;
            var entity = this.View.BillBusinessInfo.GetEntity("FSaleOrderEntry");
            var entityObjs = this.View.Model.GetEntityDataObject(entity);
            if (entityObjs != null)
            {
                int index = 0;
                foreach (var entityObj in entityObjs)
                {
                    if(CheckCount(entityObj) == false)
                    {
                        this.View.ShowErrMessage(String.Format("行号：{0} 选择了编码类别，并且销售数量与出厂编码范围不相符，请修改数量或重新生成出厂编码！", index));
                        return;
                    }
                    index++;
                }
            }
            // 继续保存操作                   
            doSave = true;
            this.View.InvokeFormOperation("Save");
        }
    }
}
